package com.zking.forward.product;

import com.zking.dao.CategoryDao;
import com.zking.dao.ProductDao;
import com.zking.entity.Category;
import com.zking.entity.Product;
import com.zking.util.Tools;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

@WebServlet("/productSelectByPage")
public class ProductSelectByPage extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理请求的编码，解决中文乱码
        request.setCharacterEncoding("utf-8");
        //处理响应的编码 ，解决中文乱码
        response.setContentType("text/html;charset=utf-8");

        System.out.println("ProductSelectByPage===进来");

        int pageIndex = 1;
        String temp = request.getParameter("pageIndex");
        String temp2 = request.getParameter("classId");
        int classId = 0;
        if(temp2!=null && !temp2.isEmpty()){
            classId = Integer.parseInt(temp2);
        }
        if(temp != null && !temp.isEmpty()){
            pageIndex = Integer.parseInt(temp);
        }
        int pageSize = 4;
        int maxPage = ProductDao.getMaxPage(pageSize, classId);
        pageIndex = Math.max(1, pageIndex);
        pageIndex = Math.min(pageIndex, maxPage);

        System.out.println(pageIndex);
        System.out.println(pageSize);
        System.out.println(classId);
        List<Product> list = ProductDao.selectProductByPage(pageIndex, pageSize, classId);
        Category category = CategoryDao.getCategoryById(classId);
        List<String> imageBytes = new ArrayList<>(); // 用来存储图像。因为需要通过Base64编码，所以用单独的数组存储
        // 获取图像，并进行编码
        for (Product product : list) {
            byte[] tmpBytes = product.getEp_image_bytes();
            if(tmpBytes!=null){
                imageBytes.add(Tools.bytesToString(tmpBytes));
            }else{
                imageBytes.add("");
            }
        }

        request.setAttribute("list", list);
        request.setAttribute("images", imageBytes);
        request.setAttribute("pageIndex", pageIndex);
        request.setAttribute("maxPage", maxPage);
        request.setAttribute("classId", classId);
        if(category!=null){
            request.setAttribute("className", category.getEpc_name());
        }
        request.getRequestDispatcher("product-list.jsp").forward(request, response);


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
